#include<stdio.h>
#include <stdlib.h>
#define old_len 10
#define new_len 15

typedef struct data
{
    int id;
    int grade;
} data;

//自定义realloc函数
//参数:结构体指针,需要的大小,原来的大小
data *my_realloc(data *d, size_t new, size_t old);

int main(int argc, char const *argv[])
{
    data *d1 = (data *)malloc(old_len * sizeof(data));
    for (int i = 0; i < old_len; i++)
    {
        d1[i].grade = 100;
        d1[i].id = i + 1;
    }
    //扩容
    my_realloc(d1, new_len, old_len);
    for (int i = old_len; i < new_len; i++)
    {
        d1[i].grade = 90;
        d1[i].id = i + 1;
    }
    for (int i = 0; i < new_len; i++)
    {
        printf("%d\t%d\n", d1[i].id, d1[i].grade);
    }
    return 0;
}



data *my_realloc(data *d, size_t new, size_t old)
{
    //创建一个新的动态空间
    data *new_d = (data *)malloc(new*sizeof(data));

    //需要的大小为0
    if (new == 0)
    {
        free(d);
        return NULL;
    }
    //需要的空间比原来小
    else if (new<old)
    {
        for (int i = 0; i < new; i++)
        {
            new_d[i].id = d[i].id;
            new_d[i].grade = d[i].grade;
        }
        return new_d;
    }
    //结构体指针为空
    else if (d==NULL)
    {
        data *new_d = (data *)malloc(new * sizeof(data));
        return new_d;
    }
    //new>old
    else
    {
        // 拷贝原本的数据
        for (int i = 0; i < old; i++)
        {
            new_d[i].id = d[i].id;
            new_d[i].grade = d[i].grade;
        }

        // 返回新空间
        return new_d;
    }
}